const axios = require('axios');
const { logger } = require('../config/logger');
const { HttpsProxyAgent } = require('https-proxy-agent');
const tokenService = require('./token');
const FormData = require('form-data');

class ImageTranslateService {
    constructor() {
        this.baseUrl = `${process.env.BAIDU_API_URL}/file/2.0/mt/pictrans/v1`;
    }

    async translateImage(imageBuffer, from, to, pasteType = 1) {
        try {
            logger.info('Preparing image translation request', {
                imageDataLength: imageBuffer.length,
                from,
                to,
                pasteType
            });

            const token = await tokenService.getAccessToken();

            // 构建 FormData
            const formData = new FormData();
            formData.append('image', imageBuffer, {
                filename: 'image.jpg',
                contentType: 'image/jpeg'
            });
            formData.append('from', from);
            formData.append('to', to);
            formData.append('v', '3');
            formData.append('paste', pasteType.toString());

            logger.info('Sending image translation request to Baidu API', {
                from,
                to,
                pasteType
            });

            const response = await axios({
                method: 'POST',
                url: `${this.baseUrl}?access_token=${token}`,
                headers: {
                    ...formData.getHeaders(),
                    'Accept': 'application/json'
                },
                data: formData,
                maxContentLength: Infinity,
                maxBodyLength: Infinity
            });

            logger.info('Received image translation response', {
                status: response.status,
                hasResult: !!response.data?.data,
                from: response.data?.from,
                to: response.data?.to
            });

            if (!response.data?.data) {
                throw new Error('Invalid response format from translation service');
            }

            // 处理响应
            return {
                success: true,
                result: {
                    from: response.data.from,
                    to: response.data.to,
                    pasteImg: response.data.data.pasteImg, // 整图贴合的翻译结果图片
                    sumSrc: response.data.data.sumSrc,     // 原文
                    sumDst: response.data.data.sumDst,     // 译文
                    // 如果需要分段信息，也可以返回
                    content: response.data.data.content?.map(item => ({
                        src: item.src,
                        dst: item.dst,
                        rect: item.rect,
                        points: item.points,
                        pasteImg: item.pasteImg // 如果是块区贴合模式
                    })) || []
                },
                log_id: Date.now().toString()
            };

        } catch (error) {
            logger.error('Image translation error', {
                error: error.message,
                details: error.response?.data,
                status: error.response?.status
            });

            throw new Error(`Image translation failed: ${error.response?.data?.error_msg || error.message}`);
        }
    }
}

module.exports = new ImageTranslateService();